package server.service.impl;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import server.common.R;
import server.dao.ChatGroupMapper;
import server.dao.ChatGroupUserMapper;
import server.dao.UserMapper;
import server.entity.ChatGroup;
import server.entity.ChatGroupUser;
import server.entity.User;
import server.service.ChatGroupService;
import server.service.SessionService;
import server.service.factories.SessionServiceFactory;
import server.utils.SqlSessionUtil;
import io.netty.channel.Channel;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.session.SqlSession;

import java.util.List;
import java.util.Objects;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
public class ChatGroupServiceImpl implements ChatGroupService {
    private SqlSession session;
    private ChatGroupMapper chatGroupMapper;
    private ChatGroupUserMapper chatGroupUserMapper;
    private UserMapper userMapper;
    private SessionService sessionService= SessionServiceFactory.getSessionService();

    private void init() {
        session=SqlSessionUtil.getSession();
        chatGroupMapper = session.getMapper(ChatGroupMapper.class);
        chatGroupUserMapper = session.getMapper(ChatGroupUserMapper.class);
        userMapper = session.getMapper(UserMapper.class);
    }


    @Override
    public R<ChatGroup> createGroup(String groupName, Set<String> membersName) {
        try {
            init();
            if(StrUtil.isEmpty(groupName)){
                return R.error("组名不可为空！");
            }
            //检查群组是否存在
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup1 = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup1!=null){
                return R.error("已存在该名称的群聊！");
            }
            //新建组
            ChatGroup chatGroup =new ChatGroup();
            chatGroup.setGroupName(groupName);
            chatGroupMapper.insert(chatGroup);
            Long gid = chatGroup.getId();
            //新建组中关联
            for (String userName : membersName) {
                LambdaQueryWrapper<User> queryWrapper2=new LambdaQueryWrapper<>();
                queryWrapper2.eq(User::getUsername,userName);
                User user = userMapper.selectOne(queryWrapper2);
                if(user==null){
//                    log.info(userName+"找不到！");
                    continue;
                }
                ChatGroupUser chatGroupUser =new ChatGroupUser();
                chatGroupUser.setGid(gid);
                chatGroupUser.setUid(user.getId());
                chatGroupUserMapper.insert(chatGroupUser);
            }
            return R.success(chatGroup);
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<ChatGroup> joinMember(String groupName, String memberName)  {
        try {
            init();
            if(StrUtil.isEmpty(groupName)||StrUtil.isEmpty(memberName)){
                return R.error("组名或成员名不可为空！");
            }
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup==null){
                return R.error("不存在该组！");
            }
            LambdaQueryWrapper<User> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(User::getUsername,memberName);
            User user=userMapper.selectOne(queryWrapper1);
            if(user==null){
                return R.error("不存在该用户！");
            }
            Long uid = user.getId();
            Long gid = chatGroup.getId();
            LambdaQueryWrapper<ChatGroupUser> queryWrapper2=new LambdaQueryWrapper<>();
            queryWrapper2.eq(ChatGroupUser::getGid,gid).eq(ChatGroupUser::getUid,uid);
            ChatGroupUser chatGroupUser = chatGroupUserMapper.selectOne(queryWrapper2);
            if(chatGroupUser!=null){
                return R.error("群聊内已存在该用户！");
            }
            ChatGroupUser chatGroupUser1=new ChatGroupUser();
            chatGroupUser1.setUid(uid);
            chatGroupUser1.setGid(gid);
            chatGroupUserMapper.insert(chatGroupUser1);
            return R.success(chatGroup);
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<ChatGroup> removeMember(String groupName, String memberName)  {
        try {
            init();
            if(StrUtil.isEmpty(groupName)||StrUtil.isEmpty(memberName)){
                return R.error("组名或成员名不可为空！");
            }
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup==null){
                return R.error("不存在该组！");
            }
            LambdaQueryWrapper<User> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(User::getUsername,memberName);
            User user=userMapper.selectOne(queryWrapper1);
            if(user==null){
                return R.error("不存在该用户！");
            }
            Long uid = user.getId();
            Long gid = chatGroup.getId();
            LambdaQueryWrapper<ChatGroupUser> queryWrapper2=new LambdaQueryWrapper<>();
            queryWrapper2.eq(ChatGroupUser::getGid,gid).eq(ChatGroupUser::getUid,uid);
            ChatGroupUser chatGroupUser = chatGroupUserMapper.selectOne(queryWrapper2);
            if(chatGroupUser==null){
                return R.error("群聊内不存在该用户！");
            }
            chatGroupUserMapper.deleteById(chatGroupUser.getId());
            return R.success(groupName+"群聊删除成员"+memberName+"成功！");
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<ChatGroup> removeGroup(String groupName)  {
        try {
            init();
            if(StrUtil.isEmpty(groupName)){
                return R.error("组名不可为空！");
            }
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup==null){
                return R.error("不存在该组！");
            }
            Long gid = chatGroup.getId();
            chatGroupMapper.deleteById(gid);
            //删除组中关联
            LambdaQueryWrapper<ChatGroupUser> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(ChatGroupUser::getGid,gid);
            chatGroupUserMapper.delete(queryWrapper1);
            return R.success("删除"+groupName+"成功！");
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<Set<String>> getMembers(String groupName)  {
        try {
            init();
            if(StrUtil.isEmpty(groupName)){
                return R.error("组名不可为空！");
            }
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup==null){
                return R.error("不存在该组！");
            }
            Long gid = chatGroup.getId();
            LambdaQueryWrapper<ChatGroupUser> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(ChatGroupUser::getGid,gid);
            List<ChatGroupUser> chatGroupUsers = chatGroupUserMapper.selectList(queryWrapper1);
            Set<String> userNames = chatGroupUsers.stream().map(item -> {
                Long uid = item.getUid();
                User user = userMapper.selectById(uid);
                return user.getUsername();
            }).collect(Collectors.toSet());
            return R.success(userNames,"查询成功！");
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }

    @Override
    public R<List<Channel>> getMembersChannel(String groupName)  {
        try {
            init();
            LambdaQueryWrapper<ChatGroup> queryWrapper=new LambdaQueryWrapper<>();
            queryWrapper.eq(ChatGroup::getGroupName,groupName);
            ChatGroup chatGroup = chatGroupMapper.selectOne(queryWrapper);
            if(chatGroup==null){
                return R.error("不存在该组！");
            }
            Long gid = chatGroup.getId();
            LambdaQueryWrapper<ChatGroupUser> queryWrapper1=new LambdaQueryWrapper<>();
            queryWrapper1.eq(ChatGroupUser::getGid,gid);
            List<ChatGroupUser> chatGroupUsers = chatGroupUserMapper.selectList(queryWrapper1);
            List<Channel> channels = chatGroupUsers.stream().map(item -> {
                Long uid = item.getUid();
                User user = userMapper.selectById(uid);
                return sessionService.getChannel(user.getUsername());
            }).filter(Objects::nonNull).collect(Collectors.toList());
            return R.success(channels);
        } finally {
            SqlSessionUtil.closeSession(session);
        }
    }
}
